package com.ls.lserp.modules.trade.web;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.map.HashedMap;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.support.RequestContext;

import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.dbaccess.Entity.FinanceEntity;
import com.ls.lserp.dbaccess.Entity.VoucherDetailEntity;
import com.ls.lserp.dbaccess.Entity.VoucherEntity;
import com.ls.lserp.modules.order.entity.AuditInfo;
import com.ls.lserp.modules.sys.entity.Sequence;
import com.ls.lserp.modules.sys.utils.SequenceUtil;
import com.ls.lserp.modules.trade.entity.AccountVoucher;
import com.ls.lserp.modules.trade.entity.Settlement;
import com.ls.lserp.modules.trade.service.AccountingVoucherService;
import com.ls.lserp.modules.trade.service.SettlementService;
import freemarker.template.Configuration;
import groovy.util.ResourceException;

@Controller
@RequestMapping(value = "${adminPath}/accounting/voucher")
public class AccountingVoucherController extends BaseController{
	
	@Autowired
	// 保存 编辑 删除 方法
	private AccountingVoucherService accountingVoucherService;
	@Autowired
	Configuration freemarkerConfiguration;
	/*@ModelAttribute
	public Settlement get(@RequestParam(required=false) String id) {
		
		// 判断id是否为空
		if (StringUtils.isNotBlank(id)){
			
			// 执行查询语句 查询基本信息
			return settlementService.findDutyByID(Long.parseLong(id));
		}else{
			
			// 若为空，实例化
			return new Settlement();
		}
	}*/
	
	
	/**
	 * @Title: 画面跳转用
	 * @return url
	 */
	@RequiresPermissions("accounting:voucher:view")
	@RequestMapping(value = { "" })
	public String list(Model model) {
		// 画面跳转
		return "modules/trade/accountingVoucher";
	}
	
	@RequiresPermissions("accounting:voucher:view")
	@RequestMapping(value = { "searchList" })
	public String searchList(VoucherEntity voucherEntity, HttpServletRequest request, HttpServletResponse response,Model model) throws Exception{
		 	Map <Object, Object> listMap = new HashMap <Object, Object> ();
	        // ajax回调时使用的一览list名
	        request.setAttribute ("listNames", "accountingVoucher");
	        // 拼接字符串供分页使用
 			StringBuilder searchParam = new StringBuilder();
 			// 凭证编号
 			searchParam.append("&voucherNo=");
 			searchParam.append(voucherEntity.getVoucherNo());
 			// 会计期间（年）
 			searchParam.append("&dateYear=");
 			searchParam.append(voucherEntity.getDateYear());	
 			// 会计期间（月）
 			searchParam.append("&dateMonth=");
 			searchParam.append(voucherEntity.getDateMonth());	
	        //放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
	        request.setAttribute (Global.SEARCH_PAEAM, searchParam);
	        // 查询一览页面数据
	        Page <VoucherEntity> page = accountingVoucherService.findList (new Page <VoucherEntity> (request, response),
	        		voucherEntity);
	        // 读取文件生成字符串
	        String strUri = request.getContextPath () + Global.getAdminPath ();
	        String strHtml = "";
	        Map <String, Object> map = new HashedMap ();
	        map.put ("adminUri", strUri);
	        map.put ("accountingVoucherList", page.getList ());
	        map.put ("pageNo", page.getPageNo ());
	        map.put ("pageSize", page.getPageSize ());
	        map.put ("springMacroRequestContext", new RequestContext (request));
	        strHtml = FreeMarkerTemplateUtils
	                .processTemplateIntoString (freemarkerConfiguration.getTemplate ("accountingVoucher.ftl"), map);
	        listMap.put ("accountingVoucher", strHtml);
	        listMap.put ("page", page.getHtml ());
	        // ajax返回结果
	        return renderString (response, listMap);
	}
	
	/**
	 * 
	 * 功能：Java读取txt文件的内容 1：先获得文件句柄 2：获得文件句柄当做是输入一个字节码流，需要对这个输入流进行读取
	 * 3：读取到输入流后，需要读取生成字节流
	 * 
	 * @param filePath
	 * @return html
	 */
	public String readTxtFile(String filePath) {
		String strHtml = "";
		try {
			String encoding = "UTF-8";
			File file = new File(filePath);
			// 判断文件是否存在
			if (file.isFile()) {
				InputStreamReader read = new InputStreamReader(
						// 考虑到编码格式
						new FileInputStream(file), encoding);
				BufferedReader bufferedReader = new BufferedReader(read);
				String lingText = null;
				while ((lingText = bufferedReader.readLine()) != null) {
					strHtml += lingText;
				}
				read.close();
			} else {

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strHtml;
	}
	

	/**
	 * 创建结汇单信息窗口
	 * 
	 * @return
	 */
	@RequiresPermissions("accounting:voucher:view")
	@RequestMapping(value = {"form"})
	public String form(VoucherEntity voucherEntity, HttpServletRequest request, HttpServletResponse response,
			Model model){
		if (voucherEntity.getVoucherId() == null) {
			//voucherEntity.setVoucherNo(SequenceUtil.voucherCode("AV","sequence_accountingVoucher",4).getReturnCode());
			model.addAttribute("voucherEntity",voucherEntity);
		}else {
			AccountVoucher accountVoucher = accountingVoucherService.getInfo(voucherEntity);
			model.addAttribute("voucherEntity", accountVoucher.getVoucherEntity());
			model.addAttribute("uploadFile", accountVoucher.getUploadFile());
			model.addAttribute("voucherDetailList", accountVoucher.getVoucherDetailEntity().getVoucherDetailList());
		}
		model.addAttribute("financeItemList",accountingVoucherService.findFinanceItem());
		//返回页面地址
		return "modules/trade/accountingVoucherCreate";
	}
	
	/**
	 * 查看画面
	 */
	@RequiresPermissions("accounting:voucher:view")
	@RequestMapping(value = {"show"})
	public String show(VoucherEntity voucherEntity, HttpServletRequest request, HttpServletResponse response,Model model){
		AccountVoucher accountVoucher = accountingVoucherService.getInfo(voucherEntity);
		model.addAttribute("voucherEntity", accountVoucher.getVoucherEntity());
		model.addAttribute("uploadFile", accountVoucher.getUploadFile());
		model.addAttribute("voucherDetailList", accountVoucher.getVoucherDetailEntity().getVoucherDetailList());
		model.addAttribute("financeItemList",accountingVoucherService.findFinanceItem());
		//返回页面地址
		return "modules/trade/accountingVoucherShow";
	}
	
	/**
	 * 选择业务结算画面
	 * 
	 * @return
	 */
	@RequiresPermissions("accounting:voucher:view")
	@RequestMapping(value = {"selectFinance"})
	public String selectFinance(FinanceEntity financeEntity, HttpServletRequest request, HttpServletResponse response,
			Model model){
		model.addAttribute("financeEntity",financeEntity);
		//返回页面地址
		return "modules/trade/accountingVoucherSelectFinance";
	}
	
	/**
	    * 保存信息
	    * @param bookingOrders
	    * @param request
	    * @param model
	    * @param response
	    * @return
	    * @throws ResourceException 
	    */
	   @RequiresPermissions("accounting:voucher:edit")
	   @RequestMapping(value = "save")
	   @ResponseBody
	   public String save(AccountVoucher accountVoucher, HttpServletRequest request, Model model, HttpServletResponse response ) throws ResourceException {
			try {
				// 保存基准数据及子项数据
				accountingVoucherService.saveData(accountVoucher);
				// 保存成功返回提示信息
				return renderString(response,ResourcesUtil.getConfig("settlement_save_success"));
			} catch (Exception e) {
				logger.error(e.getMessage(),e);
				return renderString(response,ResourcesUtil.getConfig("settlement_save_fail"));
			}

	   }
	   
	   /**
	    * 保存信息
	    * @param bookingOrders
	    * @param request
	    * @param model
	    * @param response
	    * @return
	    * @throws ResourceException 
	    */
	   @RequiresPermissions("accounting:voucher:view")
	   @RequestMapping(value = "checkExist")
	   @ResponseBody
	   public String checkExist(VoucherEntity voucherEntity, HttpServletRequest request, Model model, HttpServletResponse response ) throws ResourceException {
		   String existFlag = "false";
		   try {
			   	//查存
				voucherEntity = accountingVoucherService.checkExist(voucherEntity);
				if (voucherEntity != null) {
					existFlag = "true";
				}
				// 保存成功返回提示信息
				return renderString(response,existFlag);
			} catch (Exception e) {
				logger.error(e.getMessage(),e);
				existFlag = "error";
				return renderString(response,existFlag);
			}

	   }
	
	
	/**
	 * 逻辑删除凭证
	 * 
	 * @return
	 */
	@RequiresPermissions("accounting:voucher:edit")
	@RequestMapping(value = {"delete"})
	public String delete(AccountVoucher accountVoucher, HttpServletRequest request, HttpServletResponse response,
			Model model){
		String delFlag = "false";
		try {
			//删除
			accountingVoucherService.deleteVoucher(accountVoucher);
			delFlag = "true";
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
		//返回页面地址
		return renderString(response, delFlag);
	}
	
	/**
	 * 获取历史凭证
	 * 
	 * @return
	 */
	@RequiresPermissions("accounting:voucher:view")
	@RequestMapping(value = {"findVoucherHistory"})
	public String findVoucherHistory(AccountVoucher accountVoucher, HttpServletRequest request, HttpServletResponse response,
			Model model){
		List<VoucherDetailEntity> vList = new ArrayList<>();
		try {
			vList = accountingVoucherService.findVoucherHistory(accountVoucher);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
		}
		//返回页面地址
		return renderString(response, vList);
	}
	
	

}
